<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;
class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
      
        $this->middleware('guest')->except('logout');
    }

    public function username()
    {
        return 'mobile';
    }



    public function sendsms(Request $request)
    {
        $key = $request->mobile;
        if(Cache::has($key))
        {
            /* return [
                'Statu' => 0,
                'Msg' => '您已经发送验证码，请耐心等待.'
            ]; */
        }
        if(isset($request->type) && $request->type=='reset')
        {
            $tpl_id = '62896';
            $ruls = [
                'mobile' => [
                    'required',
                    Rule::exists('users')->where(function ($query) use ($request) {
                        $query->where('mobile', $request->mobile);
                    })
                ],
                //'code' => 'required|size:5|captcha'
            ];
        }else {
            $tpl_id = '57473';
            $ruls = [
                'mobile' => 'required|unique:users|size:11',
                //'code' => 'required|size:5|captcha'
            ];
        }
        $request->validate($ruls,[
            'mobile.required' => '手机号必须填写.',
            'mobile.unique' => '手机号已经重复.',
            'code.required' => '验证码必须填写.',
            'code.size' => '验证码长为:size.',
            'code.captcha' => '验证码错误,请点击验证码刷新.',
            'mobile.size' => '手机号长为:size.',
            'mobile.exists' => '不存在用户.'
        ]);

        $number = rand(1000, 9999);

        //存入验证码
        Cache::put($key, $number, 3);

        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL

        $smsConf = array(
            'key'   => 'ec3b617a13e627763f5844bbbcb0875d', //您申请的APPKEY
            'mobile'    => $request->mobile, //接受短信的用户手机号码
            'tpl_id'    => $tpl_id, //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>'#code#='.$number //您设置的模板变量，根据实际情况修改
        );

        $content = $this->juhecurl($sendUrl,$smsConf,1); //请求发送短信
        $msg = [];
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功
                $msg['Statu'] = 0;
                $msg['Msg'] = '短信发送成功，请耐心等待.';
                $msg['Content'] = $content;
            }else{
                //状态非0，说明失败
                $msg['Statu'] = 1;
                $msg['Msg'] = '短信发送失败，请稍后再试.';
                $msg['Content'] = $content;
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
            $msg['Statu'] = 2;
            $msg['Msg'] = '短信发送失败，请稍后再试.';
            $msg['Content'] = $content;
        }

        return $msg;

    }
    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    private function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
}
